package com.jason.accountmd.dao;

import com.jason.accountmd.mapper.AccountMapper;
import com.jason.accountmd.service.localacc.LocAccountService;
import groovy.util.logging.Commons;
import io.seata.rm.tcc.api.BusinessActionContext;
import org.apache.shardingsphere.api.hint.HintManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Service
public class AccountDao {
    private static final Logger logger = LoggerFactory.getLogger(AccountDao.class);
    @Autowired
    private AccountMapper accountMapper;

    @Transactional(rollbackFor = RuntimeException.class)
    public String addAmount(BusinessActionContext businessActionContext, Long accId, BigDecimal amount) {
        accountMapper.addAmount(accId,amount);
        HintManager.clear();
        HintManager hintManager = HintManager.getInstance();
        hintManager.addDatabaseShardingValue("t_trans_atmo", accId);
        accountMapper.insertTransAtmo(businessActionContext.getXid(),businessActionContext.getBranchId());
        HintManager.clear();
        /*if(System.currentTimeMillis()%3 == 0) {
            throw  new RuntimeException("测试异常");
        }*/
        return "success";
    }

    @Transactional(rollbackFor = RuntimeException.class)
    public void reduceAmount(BusinessActionContext businessActionContext, Long accId, BigDecimal amount) {
        HintManager.clear();
        HintManager hintManager = HintManager.getInstance();
        hintManager.addDatabaseShardingValue("t_trans_atmo", accId);
        int result = accountMapper.updateCancelTransAtmo(businessActionContext.getXid(),businessActionContext.getBranchId());
        if(result == 0) {
           result =accountMapper.selectIfExist(businessActionContext.getXid(),businessActionContext.getBranchId());
           if(result == 0) {
               logger.info(accId+"==========空回滚，返回回滚成功============"+amount);
               return ;//正常应该是返回一个状态供后续任务继续处理
           }

           throw  new RuntimeException(accId+"==========回滚失败============"+amount);
       }
        HintManager.clear();
        accountMapper.addAmount(accId,amount.negate());
    }
}
